<?php

function get_author_list()
{
	$author_list = array();
	//select all mast editor and edit as Feature, News,Event,Download author
	$query = "SELECT `id`,`name`,`username`,`box1`,`box2` FROM `guanli` WHERE `box1`='1' OR `box2`='1' OR `box4`='1'";
	$result=mysql_query($query);
	if($result == false)
		exit(sprintf("%s%s%s",mysql_error(),__FILE__,__LINE__));
	while(($row = mysql_fetch_assoc($result)))
	{
	
		$row['Feature'] = '0';
		$row['Column']  = '1';
		$row['News'] = '0';
		$row['Event'] = '0';
		$row['Download'] = '0';
		
		if($row['box1'] == '1' or $row['box2'] == '1')
		{
			$row['Feature'] = '1';
			$row['Column']  = '0';
			$row['News'] = '1';
			$row['Event'] = '1';
			$row['Download'] = '1';
		}
			
		unset($row['box1']);
		unset($row['box2']);
		$author_list[] = $row;
	}
	/*
	$query = "SELECT `id`,`name`,`username`,`a1` AS `Feature` ,`a2` AS `Column`,`a3` AS `News`,`a4` AS `Event`,`a5` AS `Download` FROM `guanli`";
	$result=mysql_query($query);
	if($result == false)
		exit(sprintf("%s%s%s",mysql_error(),__FILE__,__LINE__));
	while(($row = mysql_fetch_assoc($result)))
	{
		$author_list[] = $row;
	}*/
	return $author_list;
}
function get_autho_name_by_loginname($loginName)
{
	$query = sprintf("SELECT `name`  FROM `guanli` WHERE `username`='%s'",mysql_real_escape_string($loginName));
	$result=mysql_query($query);
	$username = '';
	if($result)
	{
		if(($row = mysql_fetch_assoc($result)))
		{
			$username = $row['name'];
		}
	}
	return $username;
}
function get_article_page_url_by_type($type)
{
	$url = 'contacta.php';
	switch($type)
	{	
		case '2':
		$url = 'contactb.php';
		break;
		case '3':
		$url = 'contactc.php';
		break;
		case '4':
		$url = 'contactd.php';
		break;
	}
	return $url;
}
function get_article_page_style_css_file_by_catalog($catalog)
{
	$css = 'page-stylea.css';
	switch($catalog)
	{	
		case 'Feature':
		$css = 'page-stylea.css';
		break;
		case 'Column':
		$css = 'page-styleb.css';
		break;
		case 'News':
		$css = 'page-stylec.css';
		break;
		case 'Event':
		$css = 'page-styled.css';
		break;
	}
	return $css;
}
function get_article_page_css_file_by_catalog($catalog)
{
	$css = 'pagea.css';
	switch($catalog)
	{	
		case 'Feature':
		$css = 'pagea.css';
		break;
		case 'Column':
		$css = 'pageb.css';
		break;
		case 'News':
		$css = 'pagec.css';
		break;
		case 'Event':
		$css = 'paged.css';
		break;
	}
	return $css;
}
function get_image_gallery_js_file_by_catalog($catalog,$isHorizenMode = false)
{

	$js = 'image.gallerya.js';
	switch($catalog)
	{	
		case 'Feature':
		$js = 'image.gallerya.js';
		if($isHorizenMode)
			$js = 'image.galleryaa.js';
		break;
		case 'Column':
		$js = 'image.galleryb.js';
		if($isHorizenMode)
			$js = 'image.gallerybb.js';
		break;
		case 'News':
		$js = 'image.galleryc.js';
		if($isHorizenMode)
			$js = 'image.gallerycc.js';
		break;
		case 'Event':
		$js = 'image.galleryd.js';
		if($isHorizenMode)
			$js = 'image.gallerydd.js';
		break;
	}
	return $js;
}
function get_article_extra_read($id)
{
	$list = array();
	$query = sprintf("SELECT * FROM `news` WHERE `id`=%d",$id);
	$result=mysql_query($query);
	if($result == false)
		exit(sprintf("%s%s%s",mysql_error(),__FILE__,__LINE__));
	if(($row = mysql_fetch_assoc($result)))
	{
		for($i=1;$i<16;$i++)
		{
			if($row["c$i"] !== "1")
				continue;
			list($bigClassName,$bigClassName2) = get_catalog_name_by_index($i);
			$query2 = sprintf("SELECT * FROM `news` WHERE `BigClassName`='%s' AND `BigClassName2`='%s' AND `isok`='1' AND `id` != %d ORDER BY `id` DESC LIMIT 0,1",$bigClassName,$bigClassName2,$id);
			$result2=mysql_query($query2);
			if($result2 == false)
				exit(sprintf("%s%s%s",mysql_error(),__FILE__,__LINE__));
			if(($row2 = mysql_fetch_assoc($result2)))
					$list[] = $row2;
		}
	}
	$return_list = $list;
	if(count($list) > 5)
	{
		$key_list = array_rand($list,5);
		$return_list = array();
		foreach($key_list as $keyValue)
		{
			$return_list[] = $list[$keyValue];
		}
	}
	return $return_list;
}
function get_article_extra_read_by_catalog($catalogName,$catalogName2 = '')
{
	$list = array();
	if(strlen($catalogName2) > 0)
		$query2 = sprintf("SELECT * FROM `news` WHERE `BigClassName`='%s'  AND `isok`='1' ORDER BY `id` DESC LIMIT 0,5",$catalogName);
	else
		$query2 = sprintf("SELECT * FROM `news` WHERE `BigClassName`='%s' AND `BigClassName2`='%s' AND `isok`='1' ORDER BY `id` DESC LIMIT 0,5",$catalogName,$catalogName2);
	
	$result2=mysql_query($query2);
	if($result2 == false)
		exit(sprintf("%s%s%s",mysql_error(),__FILE__,__LINE__));
	while(($row2 = mysql_fetch_assoc($result2)))
		$list[] = $row2;
	
	return $list;
}
function get_article_random($size = 5)
{
	$list = array();
	$query = sprintf("SELECT * FROM `news` WHERE `isok`='1' ORDER BY `id` DESC LIMIT 0,%d",$size);
	$result=mysql_query($query);
	if($result == false)
		exit(sprintf("%s%s%s",mysql_error(),__FILE__,__LINE__));
	while(($row = mysql_fetch_assoc($result)))
		$list[] = $row;
	return $list;
}
function get_catalog_name_by_index($index)
{
	$i = 1;
	$ret = array();
	foreach($GLOBALS['ARTICLE_CATALOG'] as $bigClassName=>$childArray)
	{
		$breakLoop = false;
		foreach($childArray as $bigClassName2)
		{
			if($i == $index)
			{
				$ret[0] = $bigClassName;
				$ret[1] = $bigClassName2;
				$breakLoop  = true;
				break;
			}
			$i++;
		}
		if($breakLoop)
			break;
	}
	
	return $ret;
}
function html_safe($str)
{
	return htmlentities($str,ENT_COMPAT,'UTF-8');
}
function html_safe_weak($str)
{
	return preg_replace('/<script>(.*)<\/script>/is', ' ', $str);
}

function get_table_columns($tableName)
{
	//check table columns whether in cache, if not get them from database then save to cache
	if(!isset($_REQEUST['__TABLE_COLUMNS_CACHE__']) || !array_key_exists($tablename,$_REQEUST['__TABLE_COLUMNS_CACHE__']))
	{
		$query = sprintf("DESC `%s`",$tableName);
		$result=mysql_query($query);
		if($result == false)
			exit(sprintf("%s%s%s",mysql_error(),__FILE__,__LINE__));
		$columns = array();
		while(($row = mysql_fetch_assoc($result)))
		{
			$columns[$row['Field']] = $row;
		}
		$_REQEUST['__TABLE_COLUMNS_CACHE__'][$tableName] = $columns;
	}
	
	return $_REQEUST['__TABLE_COLUMNS_CACHE__'][$tableName];
}
function compose_table_sql_from_data($tableName,$data)
{
	$sql_field = '';
	$columns = get_table_columns($tableName);
	foreach($columns as $columnName=>$desc)
	{
		if(isset($data[$columnName]))
		{
				$sql_field .= sprintf("`%s`='%s',", $columnName,mysql_real_escape_string($data[$columnName]));
		}
	}
	$sql_field  = substr($sql_field,0,-1);
	return $sql_field;
}
function get_table_empty_row($tableName)
{
	$columns = get_table_columns($tableName);
	$row_data = array();
	foreach($columns as $columnName=>$desc)
	{
		$row_data[$columnName] = '';
	}
	return $row_data;
}

function utf8substr($str, $from, $len)
{
    return preg_replace('#^(?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'.$from.'}'.
                       '((?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'.$len.'}).*#s',
                       '$1',$str);
} 
 function abc($content)
 {
    
    $content=str_replace(chr(13),"",$content);
    $content=str_replace(chr(32),"",$content); 
	$content=str_replace("&nbsp;","",$content); 
	$content=str_replace("<br>","",$content); 
	$content=str_replace("</br>","",$content); 
    $content=str_replace("<p>","",$content);
    $content=str_replace("</p>","",$content);
   return trim($content);
 }
function mb_truncate($string, $length = 80, $etc = '...', $charset='UTF-8')
{
	$original_len = mb_strlen($string,$charset);
	$truncate_str = mb_strcut($string, 0, $length,$charset);
	if($original_len > $length )
		$truncate_str .= $etc;
	return $truncate_str;
}
/*HTML RENDER FUNCTION BEGIN*/
function html_rend_articles_block($data_list,$page,$max_page,$pageLink = '',$parameter = '')
{
	$hover_css_list = '.hoverlist-cl-tops'.
										',.hoverlist-fa-tops,.hoverlist-fb-tops,.hoverlist-fc-tops,.hoverlist-fd-tops'.
										',.hoverlist-na-tops,.hoverlist-nb-tops,.hoverlist-nc-tops,.hoverlist-nc-tops,.hoverlist-ne-tops,.hoverlist-nf-tops,.hoverlist-ng-tops,'.
										',.hoverlist-ev-tops,'.
										',.hoverlist-dl-tops';
	$depend_js = <<<EOT
	<script type="text/javascript">
	$(document).ready(function(){
		$("$hover_css_list").css("opacity","0");
		$("$hover_css_list").hover(function () {
			$(this).stop().animate({
				opacity: 1
			}, "fast");
		},
		function () {
			$(this).stop().animate({
				opacity: 0
			}, "fast");
		});
		});
		</script>
EOT;
echo $depend_js;
	if(strlen($pageLink) == 0)
		$pageLink = $_SERVER['PHP_SELF'];
		
	$list_css_val = 'list-b';
	$request_uril = $_SERVER['REQUEST_URI'];
	
	if(strpos($request_uril,'feature') !== false)
	{
		$list_css_val = 'list-b';
	}
	if(strpos($request_uril,'column') !== false)
	{
		$list_css_val = 'list-bb';
	}
	if(strpos($request_uril,'news') !== false)
	{
		$list_css_val = 'list-bc';
	}
	if(strpos($request_uril,'event') !== false)
	{
		$list_css_val = 'list-bd';
	}
	

	$html = '<div id="'.$list_css_val.'"  class="clearfix">';
  echo $html;
	foreach($data_list as $data)
	{
		html_rend_article_block($data);
	}
	
	if($max_page > 1)
	{
	$html = '<div id="page"><div class="page1"><ul>';
	echo $html;
	if($page < $max_page)
	{
		$nextPage = $page+1;
    $html = '<li> <a href="'.$pageLink.'?'.$parameter.'&page='.$nextPage.'"><img src="images/page-older.gif" width="61" height="19" /></a></li>';
		echo $html;
	 }
	 
	if($page > 1)
	{
		$prevPage = $page-1;
		$html = '<li><a href="'.$pageLink.'?'.$parameter.'&page='.$prevPage.'"><img src="images/page-newer.gif" width="61" height="19" /></a></li>';
		echo $html;
	}
		$html = '</ul></div></div>';	
		echo $html;
	}
	
	$html = '</div>';	

	echo $html;
}

function html_rend_article_block($data)
{
	$img_src = sprintf("upfiles/%s-x125.jpg",html_safe($data['images1']));
	$img = $data['images1']?"<img src='$img_src' />":'';
	$addtime = date("Y-m-d",strtotime($data['addtime']));
	$addnamedisplay = html_safe($data['addnamedisplay']);
	$title = html_safe($data['title']);
	
	$link = sprintf("%s?id=%d",get_article_page_url_by_type($data['lb']),$data['id']);
	//$content =  utf8substr(strip_tags(abc($data['content'])),0,constant('MAX_SUMMARY_ARTICLE_LEN'));
	$content =  utf8substr(strip_tags($data['content']),0,constant('MAX_SUMMARY_ARTICLE_LEN'));
	//delete taile not complete blank
	$last_and_pose = strrpos($content,'&');
	$las_comma_pose = strrpos($content,';');
	if($last_and_pose  !== false)
	{
		if($las_comma_pose === false)
		{
			$content = substr($content,0,$last_and_pose);
		}else{
			if($las_comma_pose < $last_and_pose)
			{
				$content = substr($content,0,$last_and_pose);
			}
		}
	}

	$css1 = '';
	$css2 = '';
	if($data['BigClassName'] == 'Feature')
	{
		switch($data['BigClassName2'])
		{
			case 'issue':
				$css1 = 'list-fa-tops';
				$css2 = 'hoverlist-fa-tops';
			break;
			case 'collection':
				$css1 = 'list-fb-tops';
				$css2 = 'hoverlist-fb-tops';
			break;
			case 'people':
				$css1 = 'list-fc-tops';
				$css2 = 'hoverlist-fc-tops';
			break;
			case 'shops':
				$css1 = 'list-fd-tops';
				$css2 = 'hoverlist-fd-tops';
			break;
		}
	}
	if($data['BigClassName'] == 'Column')
	{
			$css1 = 'list-cl-tops';
			$css2 = 'hoverlist-cl-tops';
	}
	if($data['BigClassName'] == 'News')
	{
			$css1 = 'list-na-tops';
			$css2 = 'hoverlist-na-tops';
			switch($data['BigClassName2'])
			{
				case 'flavor':
					$css1 = 'list-na-tops';
					$css2 = 'hoverlist-na-tops';
				break;
				case 'design':
					$css1 = 'list-nb-tops';
					$css2 = 'hoverlist-nb-tops';
				break;
				case 'fashion':
					$css1 = 'list-nc-tops';
					$css2 = 'hoverlist-nc-tops';
				break;
				case 'technology':
					$css1 = 'list-nd-tops';
					$css2 = 'hoverlist-nd-tops';
				break;
				case 'travel':
					$css1 = 'list-ne-tops';
					$css2 = 'hoverlist-ne-tops';
				break;
				case 'arts':
					$css1 = 'list-nf-tops';
					$css2 = 'hoverlist-nf-tops';
				break;
				case 'leisure':
					$css1 = 'list-ng-tops';
					$css2 = 'hoverlist-ng-tops';
				break;
			}
	}
	
	if($data['BigClassName'] == 'Event')
	{
			$css1 = 'list-ev-tops';
			$css2 = 'hoverlist-ev-tops';
	}
	
$html = <<<EOT
		 <div class="list-b1">
  <div class="list-b1-photo-tab">
  <div class="list-b1-photo">
  	$img
    </div>
     <a href="$link">
<div class="$css1"><div class="$css2">
</div></div></a>
    </div>
    <div class="list-b1-infor">
    <div class="list-b1-date">$addtime</div>
     <div class="list-b1-name"> $addnamedisplay</div>
     </div>
      <h3><a href="$link">$title</a></h3>
     <p >
     		$content
       </p>
  </div>
EOT;

echo $html;
}
/*HTML RENDER FUNCTION END*/


//is mobile access
function is_mobile_access(&$detailInfo = false)
{
	$detailInfo = array('isipad'=>false);
	$mobile_browser = '0';

	if (preg_match('/(up.browser|up.link|mmp|symbian|smartphone|midp|wap|phone|android)/i', strtolower($_SERVER['HTTP_USER_AGENT']))) {
		$mobile_browser++;
	}

	if ((strpos(strtolower($_SERVER['HTTP_ACCEPT']),'application/vnd.wap.xhtml+xml') > 0) or ((isset($_SERVER['HTTP_X_WAP_PROFILE']) or isset($_SERVER['HTTP_PROFILE'])))) {
		$mobile_browser++;
	}

	$mobile_ua = strtolower(substr($_SERVER['HTTP_USER_AGENT'], 0, 4));
	$mobile_agents = array(
    'w3c ','acs-','alav','alca','amoi','audi','avan','benq','bird','blac',
    'blaz','brew','cell','cldc','cmd-','dang','doco','eric','hipt','inno',
    'ipaq','java','jigs','kddi','keji','leno','lg-c','lg-d','lg-g','lge-',
    'maui','maxo','midp','mits','mmef','mobi','mot-','moto','mwbp','nec-',
    'newt','noki','oper','palm','pana','pant','phil','play','port','prox',
    'qwap','sage','sams','sany','sch-','sec-','send','seri','sgh-','shar',
    'sie-','siem','smal','smar','sony','sph-','symb','t-mo','teli','tim-',
    'tosh','tsm-','upg1','upsi','vk-v','voda','wap-','wapa','wapi','wapp',
    'wapr','webc','winw','winw','xda ','xda-','iPhone');

	if (in_array($mobile_ua,$mobile_agents)) {
		$mobile_browser++;
	}
	$row_http_user_agent = strtolower($_SERVER['HTTP_USER_AGENT']);
	if(strpos($row_http_user_agent,'iphone') !== false)
	{
		$mobile_browser++;
	}
	if( strpos($row_http_user_agent,'ipad') !== false)
	{
		$detailInfo['isipad'] = true;
		$mobile_browser++;
	}
	if (array_key_exists('ALL_HTTP', $_SERVER) && strpos(strtolower($_SERVER['ALL_HTTP']),'OperaMini') > 0) {
		$mobile_browser++;
	}

	if (array_key_exists('HTTP_USER_AGENT', $_SERVER) && strpos(strtolower($_SERVER['HTTP_USER_AGENT']),'windows') > 0) {
		$mobile_browser = 0;
	}

	return $mobile_browser > 0;
}
/*** KEY VALUE BEGIN***/
function setGlobalValue($key,$value)
{
	$query = sprintf("REPLACE INTO `key_value` SET `key`='%s',`value`='%s'",mysql_real_escape_string($key),mysql_real_escape_string($value));
	$result=mysql_query($query);
	if($result == false)
		exit(sprintf("%s%s%s",mysql_error(),__FILE__,__LINE__));

}
function getGlobalValue($key)
{
	$value = '';
	$query = sprintf("SELECT `value` FROM `key_value` WHERE `key`='%s'",mysql_real_escape_string($key));
	$result=mysql_query($query);
	if($result == false)
		exit(sprintf("%s%s%s",mysql_error(),__FILE__,__LINE__));
	if(($row = mysql_fetch_assoc($result)))
	{
		$value = $row['value'];
	}
	return $value;
}
/*** KEY VALUE END***/

//statistic articles number
function update_statistic_articles_number()
{

	//published
	update_statistic_articles_number_one_type('Feature','1','Feature-OK');
	update_statistic_articles_number_one_type('Column','1','Column-OK');
	update_statistic_articles_number_one_type('News','1','News-OK');
	update_statistic_articles_number_one_type('Event','1','Event-OK');
	update_statistic_articles_number_one_type('Download','1','Download-OK');
	//unpublished
	update_statistic_articles_number_one_type('Feature','0','Feature-NO');
	update_statistic_articles_number_one_type('Column','0','Column-NO');
	update_statistic_articles_number_one_type('News','0','News-NO');
	update_statistic_articles_number_one_type('Event','0','Event-NO');
	update_statistic_articles_number_one_type('Download','0','Download-NO');
}

function update_statistic_articles_number_one_type($catalogName,$is_ok,$p_key )
{
	$query = sprintf("SELECT count(1) AS `cn` FROM `news` WHERE `BigClassName`='%s' AND `isok`='%s'",$catalogName,$is_ok);
	$result=mysql_query($query);
	if($result == false)
		exit(sprintf("%s%s%s",mysql_error(),__FILE__,__LINE__));
	$row = mysql_fetch_assoc($result);
	$p_value = $row['cn'];
	setGlobalValue($p_key,$p_value);
}

// increase article hit number
function increase_article_hits_number($id)
{
	$query = sprintf("UPDATE `news` SET `hits`=`hits`+1 WHERE `id`=%d",$id);
	$result=mysql_query($query);
	if($result == false)
		exit(sprintf("%s%s%s",mysql_error(),__FILE__,__LINE__));
}
//get author catalog number
function get_author_catalog_number($id)
{
/*
	$catalog_name_table = array(
		1=>'Flavor',
		2=>'Design',
		3=>'Fashion',
		4=>'Technology',
		5=>'City',
		6=>'Travel',
		7=>'Arts',
		8=>'Literature',
		9=>'Opinion',	
	);*/
	$number = 1;
	$query = sprintf("SELECT * FROM guanli WHERE `id`=%d",mysql_real_escape_string($id));
	$result=mysql_query($query);
	if($result == false)
		exit(sprintf("%s%s%s",mysql_error(),__FILE__,__LINE__));
	$row = mysql_fetch_assoc($result);
	if($row)
	{
		for($i=1;$i<10;$i++)
		{
			if($row['a'.$i] == '1')
			{
				$number = $i;
				break;
			}
		}
	}
	return $number;
}

function get_article_lock_list($BigClassName,$BigClassName2)
{
	if($BigClassName == 'Feature')
	{
		$sql = sprintf("SELECT * FROM `news` WHERE `BigClassName`='%s' AND `BigClassName2`='%s' AND `lock`='Y' AND `lock_start` < now() AND `lock_end` > now()",mysql_real_escape_string($BigClassName),mysql_real_escape_string($BigClassName2));
	
	}else if($BigClassName == 'News')
	{
		if(strlen($BigClassName2) > 0)
		{
			  $sql = sprintf("SELECT * FROM `news` WHERE `BigClassName`='%s' AND `BigClassName2`='%s' AND `lock`='Y' AND `lock_start` < now() AND `lock_end` > now()",mysql_real_escape_string($BigClassName),mysql_real_escape_string($BigClassName2));

		}else{
				$sql = sprintf("SELECT * FROM `news` WHERE `BigClassName`='%s'  AND `lock2`='Y' AND `lock_start` < now() AND `lock_end` > now()",mysql_real_escape_string($BigClassName));

		}
	}else if($BigClassName == 'Column' || $BigClassName == 'Event')
	{
			$sql = sprintf("SELECT * FROM `news` WHERE `BigClassName`='%s' AND `lock`='Y' AND `lock_start` < now() AND `lock_end` > now()",mysql_real_escape_string($BigClassName));
	}
	$data_list = array();
	$result=mysql_query($sql);
	if($result == false)
		exit(sprintf("%s%s%s",mysql_error(),__FILE__,__LINE__));
	while(($row = mysql_fetch_assoc($result)))
	{
		$data_list[] = $row;
	}
	return $data_list;
}
function get_ad_lock_list($lockc)
{
	if($lockc == 'lock')
	{
		$sql = "SELECT * FROM `ad` WHERE `lock`='Y' AND `begintime`<now() AND `endtime` > now()";
	}else{
		$sql = "SELECT * FROM `ad` WHERE `lock2`='Y' AND `begintime`<now() AND `endtime` > now()";
	}
	
	$data_list = array();
	$result=mysql_query($sql);
	if($result == false)
		exit(sprintf("%s%s%s",mysql_error(),__FILE__,__LINE__));
	while(($row = mysql_fetch_assoc($result)))
	{
		$data_list[] = $row;
	}
	return $data_list;
}

function getVarEgnoreMagicQuotes($str) {
    if (get_magic_quotes_gpc()) {
        return stripslashes($str);
    } else {
        return $str;
    }
}

function delete_garbage_files_in_tmp_dir()
{
	$tmp_path = dirname(dirname(__FILE__)).'/upfiles/tmp';
	$dh = opendir($tmp_path);
	while($file = readdir($dh))
	{	
		if($file == "." || $file == ".." || !is_file($tmp_path.'/'.$file))
			continue;
		
		$f_created_time = filectime($tmp_path.'/'.$file);
		if($f_created_time < (time() - 60*3))
		{
			@unlink($tmp_path.'/'.$file);
		}
	}
}
?>